# coding: utf-8
__author__ = 'j.tommy'

from modules import User, Blog, Comment

class DBError(Exception):
    pass


def select_user_by_username(username):
    try:
        session = sessionmaker(bind=engine)
        s = session()
        user = s.query(User).filter(User.username == username).first()
        return user
    except Exception, e:
        raise DBError(e)
    finally:
        if s:
            s.close()


def select_user_by_email(email):
    try:
        session = sessionmaker(bind=engine)
        s = session()
        user = s.query(User).filter(User.email == email).first()
    except Exception, e:
        raise DBError(e)
    finally:
        if s:
            s.close()


def add_user(user):
    try:
        session = sessionmaker(bind=engine)
        s = session()
        s.add(user)
        s.commit()
    except Exception, e:
        raise DBError(e)
    finally:
        if s:
            s.close()


def change_pwd(username, new_password):
    try:
        session = sessionmaker(bind=engine)
        s = session()
        s.query(User).filter(username == username).first()
        s.password = new_password
        s.commit()
    except Exception, e:
        raise DBError(e)
    finally:
        if s:
            s.close()


def select_blog_by_username_for_pagination(username, page):
    try:
        session = sessionmaker(bind=engine)
        s = session()
        query = s.query(Blog).filter(username == username)
        offset = page._get_offset()
        query = query.offset(offset)
        query = query.limit(page.per_page)
        records = query.all()
        page.records = records
        return page
    except Exception, e:
        raise DBError(e)
    finally:
        if s:
            s.close()


def select_blog_by_id(id):
    try:
        session = sessionmaker(bind=engine)
        s = session()
        return s.query(Blog).filter(id == id).first()
    except Exception, e:
        raise DBError(e)
    finally:
        if s:
            s.close()